package main

import (
	"bufio"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"math/rand"
	"os"
	"time"
)

func main()  {
	m := make(map[string]int)
	var rand_num int
	stuname := []string{"方杰","鲁仁栋","史伟名","肖祥武","刘德华"}
	jsonFile, err := ioutil.ReadFile("stu_name.json")
	if err != nil{
		fmt.Println("error open json file")
		return
	}
	err = json.Unmarshal(jsonFile,&m)
	if err != nil{
		fmt.Println("读取错误")
	}
	for {
		fmt.Println("按任意键开始")
		reader := bufio.NewReader(os.Stdin)
		num,_ := reader.ReadByte()
		if string(num) == "q" {
			fmt.Println(m)
			break
		} else if len(stuname) == 0 {
			fmt.Println("用户已经全部抽取完成")
			fmt.Println(m)
			break
		} else{
			if len(stuname) == 1{
				rand_num = 0
			} else {
				//时间戳	从1970年1月1日 到现在的秒数
				rand.Seed(time.Now().Unix())	//加入随机种子
				rand_num = rand.Intn(len(stuname) - 1)
			}
			fmt.Printf("请%s同学回答问题 \n", stuname[rand_num])
			m[stuname[rand_num]] += 1
			marshal, err := json.Marshal(m)
			if err != nil {
				fmt.Println("json error:", err)
				return
			}
			create, err :=os.Create("stu_name.json")
			if err != nil {
				fmt.Println("json error:", err)
				return
			}
			_,err = create.Write(marshal)
			defer create.Close()
			stuname = append(stuname[:rand_num], stuname[rand_num+1:]...)
		}
	}
}
